import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import getPageTitle from '@/utils/get-page-title';
NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start();

  // 设置页面标题
  document.title = getPageTitle(to.meta.title);

  // 是否有token 有默认登陆
  const isLogin = !!store.getters.token;
  console.log('token存在', isLogin);

  if (isLogin) {
    if (to.path === '/login') {
      next({ path: '/' });
      return;
    }
    // 判断是否刷新页面
    // vuex中无数据，则为刷新页面
    if (store.state.permission.addRoutes.length === 0) {
      console.log('刷新进入，重新获取路由');
      store.dispatch('permission/generateRoutes').then(() => {
        next({ path: to.path });
      });
    } else {
      next();
    }
  } else {
    // 没登陆
    console.log('to', to.path);
    if (to.path === '/login') {
      next();
    } else {
      next({ path: '/login' });
      // bug!!! 从登陆页跳回登陆页 不触发afterEach() 解决进度条问题
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
